import React, { useState, useEffect } from 'react';
import { Slider, Button } from 'antd';
import { ComposableMap, Geographies, Geography } from 'react-simple-maps';
import chinaGeoJson from '@/assets/china.json';

// 定义数据结构，描述 admissionData 的类型
interface AdmissionData {
  [year: string]: {
    [province: string]: number; // 每个省份对应的招生人数
  };
}

const admissionData: AdmissionData = {
  "2024": {
    "北京": 59,
    "天津": 647,
    "河北": 410,
    "山西": 258,
    "内蒙古": 122,
    "辽宁": 219,
    "吉林": 143,
    "黑龙江": 133,
    "上海": 32,
    "江苏": 121,
    "浙江": 72,
    "安徽": 199,
    "福建": 143,
    "江西": 161,
    "山东": 262,
    "河南": 305,
    "湖北": 128,
    "湖南": 160,
    "广东": 91,
    "广西": 76,
    "海南": 22,
    "重庆": 73,
    "四川": 163,
    "贵州": 71,
    "云南": 65,
    "西藏": 9,
    "陕西": 105,
    "甘肃": 84,
    "青海": 25,
    "宁夏": 41,
    "新疆": 68
  },
  "2023": {
    "北京": 59,
    "天津": 645,
    "河北": 408,
    "山西": 258,
    "内蒙古": 122,
    "辽宁": 219,
    "吉林": 143,
    "黑龙江": 133,
    "上海": 24,
    "江苏": 111,
    "浙江": 54,
    "安徽": 195,
    "福建": 140,
    "江西": 157,
    "山东": 260,
    "河南": 302,
    "湖北": 128,
    "湖南": 157,
    "广东": 73,
    "广西": 72,
    "海南": 17,
    "重庆": 73,
    "四川": 160,
    "贵州": 67,
    "云南": 62,
    "西藏": 9,
    "陕西": 105,
    "甘肃": 80,
    "青海": 25,
    "宁夏": 41,
    "新疆": 68
  },
  "2022": {
    "北京": 59,
    "天津": 645,
    "河北": 408,
    "山西": 258,
    "内蒙古": 122,
    "辽宁": 219,
    "吉林": 143,
    "黑龙江": 133,
    "上海": 23,
    "江苏": 111,
    "浙江": 54,
    "安徽": 195,
    "福建": 140,
    "江西": 157,
    "山东": 260,
    "河南": 302,
    "湖北": 128,
    "湖南": 157,
    "广东": 73,
    "广西": 72,
    "海南": 17,
    "重庆": 73,
    "四川": 160,
    "贵州": 67,
    "云南": 62,
    "西藏": 9,
    "陕西": 105,
    "甘肃": 80,
    "青海": 25,
    "宁夏": 41,
    "新疆": 68
  },
  "2021": {
    "北京": 59,
    "天津": 645,
    "河北": 408,
    "山西": 258,
    "内蒙古": 122,
    "辽宁": 219,
    "吉林": 143,
    "黑龙江": 133,
    "上海": 23,
    "江苏": 111,
    "浙江": 54,
    "安徽": 195,
    "福建": 140,
    "江西": 157,
    "山东": 260,
    "河南": 302,
    "湖北": 128,
    "湖南": 157,
    "广东": 73,
    "广西": 72,
    "海南": 17,
    "重庆": 73,
    "四川": 160,
    "贵州": 67,
    "云南": 62,
    "西藏": 9,
    "陕西": 105,
    "甘肃": 80,
    "青海": 25,
    "宁夏": 41,
    "新疆": 68
  }
};

// 定义 Geographies 和 Geography 的类型
type GeographyType = {
  rsmKey: string;
  properties: {
    name: string;
  };
};

const Centerc: React.FC = () => {
  // 创建一个引用
  const [year, setYear] = useState(2021);
  const [isRunning, setIsRunning] = useState(false); // 控制是否自动更新
  const [intervalId, setIntervalId] = useState<NodeJS.Timeout | null>(null); // 用来存储定时器ID
  const [tooltip, setTooltip] = useState<{ visible: boolean; content: string; x: number; y: number }>({
    visible: false,
    content: '',
    x: 0,
    y: 0
  });

  const [highlightedProvince, setHighlightedProvince] = useState<string | null>(null);

  const [currentData, setCurrentData] = useState(admissionData[year]); // 当前年份的数据

  // 每隔3秒自动更新年份
  useEffect(() => {
    if (isRunning) {
      const id = setInterval(() => {
        setYear((prevYear) => {
          return prevYear === 2024 ? 2021 : prevYear + 1;
        });
      }, 3000); // 每3秒更新一次年份
      setIntervalId(id); // 保存定时器ID
    } else {
      if (intervalId) {
        clearInterval(intervalId); // 停止定时器
      }
    }
    return () => {
      if (intervalId) {
        clearInterval(intervalId); // 清理定时器
      }
    };
  }, [isRunning]); // 每当 isRunning 变化时重新设置定时器

  // 切换自动更新状态
  const toggleAutoUpdate = () => {
    setIsRunning((prev) => !prev); // 切换状态
  };

  useEffect(() => {
    // 每当年份变化时，更新 currentData
    setCurrentData(admissionData[year]);
  }, [year]);

  // 根据数据值确定颜色的深浅（可以用线性渐变或者颜色映射）
  const getColor = (value: number, isHighlighted: boolean) => {
    const max = Math.max(...Object.values(currentData)); // 获取数据中的最大值
    const scale = (value / max) * 255; // 计算颜色深浅

    // 调整颜色范围，使颜色更加浅
    const adjustedScale = Math.min(scale * 0.6, 255); // 控制颜色的变动幅度

    if (isHighlighted) {
      return `rgb(255, 69, 0)`; // 高亮颜色（橙色）
    }
    return `rgb(255, 255, ${255 - adjustedScale})`; // 使颜色变得更浅，减少蓝色的深度
  };

  return (
    
    <div
    style={{
      width: '100%',
      height: '100%',
      padding: '0px',
      
      borderRadius: '10px', // 圆角
      backgroundImage: 'url(/assets/背景.jpg)', // 背景图片路径
      backgroundSize: 'cover', // 背景图覆盖整个容器
      backgroundPosition: 'center', // 背景图居中
      backgroundRepeat: 'no-repeat' // 背景图不重复
    }}
  >
      {/* 时间轴控件 */}
      
      <div style={{ marginBottom: '0px', marginLeft: '100px' }}>
        
        <Slider
          min={2021}
          max={2024}
          step={1}
          value={year}
          onChange={(value) => setYear(value)}
          marks={{
            2021: '2021',
            2022: '2022',
            2023: '2023',
            2024: '2024'
          }}
          style={{ width: '80%' }}
        />
        {/* 自动更新按钮 */}
        <Button
          style={{ marginLeft: '10px' }}
          type="primary" // 设置按钮的类型为 "primary"
          className={isRunning ? 'ant-btn-danger' : ''} // 根据 isRunning 状态动态设置按钮样式
          onClick={toggleAutoUpdate}
        >
          {isRunning ? '停止自动更新' : '开始自动更新'}
        </Button>
      </div>
      <ComposableMap
        projection="geoMercator"
        projectionConfig={{
          scale: 545, // 缩放比例
          center: [105, 35] // 中心点坐标，设置为中国的经纬度中心
        }}
        width={800}
        height={500}
      >
        <Geographies geography={chinaGeoJson}>
          {({ geographies }: { geographies: GeographyType[] }) =>
            geographies.map((geo: GeographyType) => {
              const provinceName = geo.properties.name;
              const provinceValue = currentData[provinceName];
              const isHighlighted = provinceName === highlightedProvince;

              const color = provinceValue !== undefined ? getColor(provinceValue, isHighlighted) : '#d3d3d3'; // 如果没有数据，显示灰色

              // 设置提示框显示的内容
              const tooltipContent =
                provinceValue !== undefined
                  ? `${provinceName}: ${provinceValue} 人`
                  : `${provinceName}: 0人`;

              return (
                <g key={geo.rsmKey}>
                  <Geography
                    geography={geo}
                    fill={color}
                    stroke="#000"
                    onMouseEnter={(event: { clientX: any; clientY: any; }) => {
                      const { clientX, clientY } = event;
                      setTooltip({
                        visible: true,
                        content: tooltipContent,
                        x: clientX + 10,
                        y: clientY + 10
                      });
                      setHighlightedProvince(provinceName);
                    }}
                    onMouseLeave={() => {
                      setTooltip({ ...tooltip, visible: false });
                      setHighlightedProvince(null);
                    }}
                  />
                </g>
              );
            })
          }
        </Geographies>
      </ComposableMap>

      {/* 自定义提示框 */}
      {tooltip.visible && (
        <div
          style={{
            position: 'absolute',
            top: tooltip.y - 140,
            left: tooltip.x - 440,
            padding: '5px 10px',
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
            color: '#fff',
            borderRadius: '5px',
            fontSize: '14px',
            pointerEvents: 'none',
            whiteSpace: 'nowrap'
          }}
        >
          {tooltip.content}
        </div>
      )}
    </div>
  );
};

export default Centerc;
